package br.com.future.controllers;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import br.com.future.constants.UptimeSingleton;
import br.com.future.securityContext.SecurityContext;
import br.com.future.securityContext.SecurityContextUtils;


/**
 * This controller is a use-less controller used first for study.<br>
 * Nowadays this controller is returning a HTML page with all headers passed by requester.
 *
 * @author Rafael Castanho Ferreira (mailto: rafa.ferreira@gmail.com)
 * @since 01-2011
 */
public class GenericController implements Controller {

	public static final String DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

		//System.out.println("Request handled - VERB[" + request.getMethod() + "]");

		// Get SecurityContext from request, some friendly interceptor already did our work! Woohoolll
		SecurityContext sc = SecurityContextUtils.getSecurityContextFromRequest(request);

		UptimeSingleton.getInstance();
		sc.addHeader("Uptime", (System.currentTimeMillis() - UptimeSingleton.getStartupTime()) + "");

		response.setStatus(HttpServletResponse.SC_OK);
		response.setContentType("text/html; charset=UTF-8");

		PrintWriter out = response.getWriter();
		String title = "Servlet Example: Showing Request Headers";
		out.println(headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n"
				+ "<B>Request Method: </B>" + request.getMethod() + "<BR>\n" + "<B>Request URI: </B>"
				+ request.getRequestURI() + "<BR>\n" + "<B>Request Protocol: </B>" + request.getProtocol()
				+ "<BR><BR>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n"
				+ "<TH>Header Name<TH>Header Value");

		for (Header oneHeader : sc.getHeaders()) {
			out.println("<TR><TD>" + oneHeader.getName());
			out.println("    <TD>" + oneHeader.getValue());
		}
		out.println("</TABLE>\n</BODY></HTML>");

		return null;
	}

	public static String headWithTitle(String title) {
		return (DOCTYPE + "\n" + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
	}
}
